package com.lq.dubbo.rocketmq.shop.mq;

import com.alibaba.fastjson.JSON;
import com.lq.dubbo.rocketmq.shop.constant.ShopCode;
import com.lq.dubbo.rocketmq.shop.entity.MQEntity;
import com.lq.dubbo.rocketmq.shop.mapper.TradeOrderMapper;
import com.lq.dubbo.rocketmq.shop.shop_pojo.TradeOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @program: dubborocketmqshop
 * @description: 消息监听
 * 因为订单回退,用户,商品,订单,优惠券系统登都需要监听做相应设置,所以messageModel(消费模式)设置为广播消费模式
 * @author: LQ
 * @create: 2021-06-24 16:25
 */
@Component
@Slf4j
@RocketMQMessageListener(topic = "${mq.order.topic}", consumerGroup = "${mq.order.consumer.group.name}", messageModel = MessageModel.BROADCASTING)
public class CancelMqListener implements RocketMQListener<MessageExt> {

    @Autowired
    private TradeOrderMapper orderMapper;

    // MessageExt 继承Message 有消息ID
    @Override
    public void onMessage(MessageExt messageExt) {
        MQEntity mqEntity = null;
        try {
            // 获取消息
            String body = new String(messageExt.getBody(), "UTF-8");
            mqEntity = JSON.parseObject(body, MQEntity.class);
            log.info("接收消息成功");
            // 查询订单
            TradeOrder order = orderMapper.selectByPrimaryKey(mqEntity.getOrderId());
            // 修改状态
            order.setOrderStatus(ShopCode.SHOP_ORDER_MESSAGEE_STATUS_ISPAID.getCode());
            int r = orderMapper.updateByPrimaryKey(order);
            log.info("订单[" + order.getOrderId() + "]状态设置为取消");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.info("订单取消订单失败");
        }
    }
}